package com.yuyou.fn.tradingservice.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.service.ISmsService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.ITeacherService;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.entity.BusTeam;
import com.yuyou.fn.platform.entity.SysDataPermission;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.platform.service.IBusTeamService;
import com.yuyou.fn.platform.service.ISysDataPermissionService;
import com.yuyou.fn.platform.service.ISysUserService;
import com.yuyou.fn.settlement.entity.MainAccount;
import com.yuyou.fn.settlement.service.IMainAccountService;
import com.yuyou.fn.tradingservice.entity.ServiceMerchant;
import com.yuyou.fn.tradingservice.mapper.ServiceMerchantMapper;
import com.yuyou.fn.tradingservice.service.IServiceMerchantService;
import com.yuyou.fn.tradingservice.vo.ServiceMerchantVo;
import com.yuyou.fn.tradingservice.vo.TeamVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * ServiceMerchant 表数据服务层接口实现类
 *
 */
@Service
public class ServiceMerchantServiceImpl extends SuperServiceImpl<ServiceMerchantMapper, ServiceMerchant,Long> implements IServiceMerchantService {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IBusTeamService busTeamService;

    @Resource
    private IMainAccountService mainAccountService;

    @Resource
    private ISysDataPermissionService sysDataPermissionService;

    @Resource
    private ITeacherService teacherService;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private ISmsService smsService;

    @Override
    @Transactional
    public Long saveOrUpdate(ServiceMerchantVo serviceMerchantVo) {
       /* Integer status=serviceMerchantVo.getStatus();
        Long merchantId=serviceMerchantVo.getMerchantId();
        ServiceMerchant serviceMerchant=this.findById(merchantId);
        *//*审核通过创建业务组用户*//*
        if (status==1){
            BusTeam busTeam=new BusTeam();
            busTeam.setTeamId(IdWorker.getId());
            busTeam.setCreateTime(TimeUtils.now());
            busTeam.setUpdateTime(TimeUtils.now());
           // busTeam.setName(serviceMerchant.getBusTeamName());
            busTeam.setAreaTeamId(serviceMerchant.getAreaTeamId());
          //  busTeam.setAreaTeamName(serviceMerchant.getAreaTeamName());
            busTeamService.insert(busTeam);

            SysUser user=new SysUser();
            BeanUtils.copyProperties(user,serviceMerchant);
           *//* user.setTeamId(busTeam.getTeamId());
            user.setBusTeamName(busTeam.getName());*//*
            user.setAvatarUrl(serviceMerchant.getHeadImageUrl());
            user.setRealName(serviceMerchant.getMerchantName());
            user.setSellerId(serviceMerchant.getMerchantId());
            user.setPassword(serviceMerchant.getMerchantPassword());
            user.setStatus(1);
            user.setUpdateTime(TimeUtils.now());
            user.setCreateTime(TimeUtils.now());
            sysUserService.insertSelective(user);

        }
        ServiceMerchant serviceMerchant1=new ServiceMerchant();
        serviceMerchant1.setMerchantId(serviceMerchant.getMerchantId());
        serviceMerchant1.setStatus(serviceMerchantVo.getStatus());
        serviceMerchant1.setUpdateTime(TimeUtils.now());
        this.updateSelectiveById(serviceMerchant1);
        return  serviceMerchant.getMerchantId();*/
        return  null;
    }

    @Override
    public Long countByPhoneNoAndStatus(String phoneNo, Integer status) {
        Example<ServiceMerchant> serviceMerchantExample=ServiceMerchant.createExample();
        Example.Criteria criteria=serviceMerchantExample.createCriteria();
        criteria.andEqualTo("phoneNo",phoneNo);
        criteria.andEqualTo("status",status);
        return this.countByExample(serviceMerchantExample);
    }

    @Override
    public Page<ServiceMerchant> findMerchantPage(ServiceMerchantVo serviceMerchant, int pageNo, int pageSize) {
        if (serviceMerchant.getBeginTime()!=null && serviceMerchant.getEndTime()!=null && serviceMerchant.getEndTime().before(serviceMerchant.getBeginTime())){
            throw new BusException("结束日期必须大于开始日期");
        }

        Example<ServiceMerchant> example = ServiceMerchant.createExample();
        Example.Criteria criteria = example.createCriteria();
        //CriteriaUtils.fillCondition(criteria,serviceMerchant);
        criteria.andNotEqualTo("status",3);//原有的账号不进入审核
        if (StringUtils.isNotEmpty(serviceMerchant.getMerchantName())){
            criteria.andLike("merchantName","%"+serviceMerchant.getMerchantName()+"%");
        }
        if(StringUtils.isNotEmpty(serviceMerchant.getPhoneNo())){
            criteria.andLike("phoneNo","%"+serviceMerchant.getPhoneNo()+"%");
        }
        if (serviceMerchant.getBeginTime()!=null){

            criteria.andGreaterThanOrEqualTo("createTime",TimeUtils.startOfDate(serviceMerchant.getBeginTime()));
        }
        if (serviceMerchant.getEndTime()!=null){
            criteria.andLessThanOrEqualTo("createTime",TimeUtils.endOfDate(serviceMerchant.getEndTime()));
        }
        if (serviceMerchant.getStatus()!=null){
            criteria.andEqualTo("status",serviceMerchant.getStatus());
        }
        example.orderBy("createTime").desc();
        return findPageByExample(example,pageNo,pageSize);
    }



    @Override
    public List<ServiceMerchant> findLimitMerchant(Integer limit) {
        Example<ServiceMerchant> example = ServiceMerchant.createExample();

        example.limit(limit);
        return findListByExample(example);
    }

    @Override
    @Transactional
    public void save(ServiceMerchantVo serviceMerchantVo) {
        /*添加业务组*/
   /*     Date now=TimeUtils.now();
        BusTeam busTeam=new BusTeam();
        busTeam.setTeamId(IdWorker.getId());
        busTeam.setAreaTeamId(serviceMerchantVo.getAreaTeamId());
        busTeam.setAreaTeamName(serviceMerchantVo.getAreaTeamName());
        busTeam.setCreateTime(now);
        busTeam.setUpdateTime(now);
        busTeam.setName(serviceMerchantVo.getMerchantName());
        busTeamService.insertSelective(busTeam);*/

    /*    //新增用户
        SysUser user=new SysUser();
        BeanUtils.copyProperties(user,serviceMerchantVo);
        user.setSellerId(IdWorker.getId());
        user.setUpdateTime(TimeUtils.now());
        user.setCreateTime(TimeUtils.now());
        user.setRealName(serviceMerchantVo.getMerchantName());
        user.setPassword(serviceMerchantVo.getMerchantPassword());
        user.setAvatarUrl(serviceMerchantVo.getHeadImageUrl());
        sysUserService.insertSelective(user);
*/

        /*服务商*/
        ServiceMerchant serviceMerchant = new ServiceMerchant();
        //serviceMerchant.setTeamId(busTeam.getTeamId());
        BeanUtils.copyProperties(serviceMerchant,serviceMerchantVo);
        serviceMerchant.setMerchantId(IdWorker.getId());
        // serviceMerchant.setUserId(serviceMerchant.getMerchantId());
        serviceMerchant.setCreateTime(TimeUtils.now());
        serviceMerchant.setUpdateTime(TimeUtils.now());
        if (serviceMerchant.getRoleType()==2 && serviceMerchant.getBelongAreaTeamId()==null){
            throw new BusException("注册业务组必须选择区域");
        }
        if (serviceMerchant.getBelongAreaTeamId()!=null){
            AreaTeam areaTeam=areaTeamService.findById(serviceMerchant.getBelongAreaTeamId());
            serviceMerchant.setBelongAreaTeamName(areaTeam.getName());
        }
        // serviceMerchant.setSellerId(user.getSellerId());
        insertSelective(serviceMerchant);
    }



    @Override
    @Transactional
    public void auditMerchants(List<Long> merchantIds, Integer status) {
        this.changeStatusByMerchantIds(merchantIds,status);
        if (status==1){
            List<ServiceMerchant> serviceMerchantList=this.findByIds(merchantIds);
            for (ServiceMerchant serviceMerchant:serviceMerchantList){
                this.auditPassMerchant(status,serviceMerchant);
            }
        }
    }

    @Override
    @Transactional
    public void auditMerchants(ServiceMerchantVo serviceMerchantVo) {
        ServiceMerchant serviceMerchant=new ServiceMerchant();
        BeanUtils.copyProperties(serviceMerchant,serviceMerchantVo);
        if (serviceMerchant.getStatus()==2 && StringUtils.isEmpty(serviceMerchant.getRemarks())){
            throw new BusException("审核不通过必须填写原因");
        }
        serviceMerchant.setAuditTime(TimeUtils.now());
        this.updateSelectiveById(serviceMerchant);
        if (serviceMerchant.getStatus()==1){
            serviceMerchant=this.findById(serviceMerchant.getMerchantId());
            this.auditPassMerchant(serviceMerchant.getStatus(),serviceMerchant);
        }else if (serviceMerchant.getStatus()==2){
            try {
                smsService.send(Arrays.asList(serviceMerchant.getPhoneNo()),"很抱歉，您在“誉优品学-服务平台”所注册的账号尚未通过审核，理由：（"+serviceMerchant.getRemarks()+"） 。请修改之后重新提交，谢谢！");
            }catch (Exception e){

            }
        }
    }

    @Override
    @Transactional
    public void auditPassMerchant(Integer status, ServiceMerchant serviceMerchant) {
        SysUser sysUser=this.addSysUserByMerchant(serviceMerchant,1);
        AreaTeam areaTeam=areaTeamService.findById(serviceMerchant.getBelongAreaTeamId());
        if (areaTeam!=null){
            serviceMerchant.setBelongAreaTeamName(areaTeam.getName());
        }
        if (serviceMerchant.getRoleType()==1){//区域角色添加区域权限
            List<BusTeam> busTeamList=busTeamService.findBusTeamByAreaTeamIds(Arrays.asList(serviceMerchant.getBelongAreaTeamId()));
            List<SysDataPermission> sysUserDataPermissionList=new ArrayList<>(busTeamList.size()+1);
            SysDataPermission areaPermission=new SysDataPermission();
            areaPermission.setResourceId(serviceMerchant.getBelongAreaTeamId());
            areaPermission.setResourceType(0);
            sysUserDataPermissionList.add(areaPermission);
            for (BusTeam busTeam:busTeamList){
                SysDataPermission sysUserDataPermission=new SysDataPermission();
                sysUserDataPermission.setResourceId(busTeam.getBusTeamId());
                sysUserDataPermission.setResourceType(1);
                sysUserDataPermissionList.add(sysUserDataPermission);
            }
            sysDataPermissionService.saveDataPermission(sysUser.getUserId(),sysUserDataPermissionList);
        }else if (serviceMerchant.getRoleType()==2){
            SysDataPermission sysUserDataPermission=new SysDataPermission();
            BusTeam busTeam=this.addBusTeamByMerchant(serviceMerchant);
            sysUserDataPermission.setResourceId(busTeam.getBusTeamId());
            sysUserDataPermission.setResourceType(1);
            sysDataPermissionService.saveDataPermission(sysUser.getUserId(),Arrays.asList(sysUserDataPermission));
        }else if (serviceMerchant.getRoleType()==3){
            this.addTeacherByMerchant(serviceMerchant,1);
        }
        try {
            smsService.send(Arrays.asList(sysUser.getPhoneNo()),"恭喜您！您在“誉优品学-服务平台”所注册的账号"+sysUser.getUsername()+"已通过审核，您可使用注册用户名或手机号进行登录，谢谢！");
        }catch (Exception e){

        }
    }


    @Override
    public void changeStatusByMerchantIds(List<Long> merchantIds, Integer status) {
        Example<ServiceMerchant> serviceMerchantExample=ServiceMerchant.createExample();
        Example.Criteria criteria=serviceMerchantExample.createCriteria();
        criteria.andIn("merchantId",merchantIds);
        ServiceMerchant serviceMerchant=new ServiceMerchant();
        serviceMerchant.setStatus(status);
        this.updateSelectiveByExample(serviceMerchant,serviceMerchantExample);
    }

    @Override
    public SysUser addSysUserByMerchant(ServiceMerchant serviceMerchant, Integer status) {

        SysUser sysUser = new SysUser();
        sysUser.setUserId(serviceMerchant.getMerchantId());
        sysUser.setUsername(serviceMerchant.getMerchantName());
       // sysUser.setRealName(serviceMerchant.getMerchantName());
        if (serviceMerchant.getStatus()==1){
            AreaTeam areaTeam=areaTeamService.findById(serviceMerchant.getBelongAreaTeamId());
            sysUser.setRealName(areaTeam.getName());
        }else if(serviceMerchant.getStatus()==2) {
            sysUser.setRealName(serviceMerchant.getBelongBusTeamName());
        }

        SysUser sysUser1=sysUserService.findByPhoneNo(serviceMerchant.getPhoneNo());
        if (sysUser1!=null){
            throw new BusException("该电话号码的用户已存在，审批失败");
        }
        sysUser.setPassword(serviceMerchant.getMerchantPassword());
        sysUser.setPhoneNo(serviceMerchant.getPhoneNo());
        sysUser.setAvatarUrl(serviceMerchant.getHeadImageUrl());
        sysUser.setIdNo(serviceMerchant.getIdNo());
        sysUser.setCreateTime(TimeUtils.now());
        sysUser.setUpdateTime(TimeUtils.now());
        sysUser.setUserType(serviceMerchant.getRoleType());
        sysUser.setStatus(status);
        sysUserService.insertSelective(sysUser);
        return sysUser;
    }

    @Override
    public Teacher addTeacherByMerchant(ServiceMerchant serviceMerchant, Integer status) {
        Teacher checkTeacher=teacherService.findTeacherByIdNo(serviceMerchant.getIdNo());
        if (checkTeacher!=null){
            throw new BusException("该身份证已存在，审核通过失败");
        }
        Teacher teacher=new Teacher();
        BeanUtils.copyProperties(teacher,serviceMerchant);
        teacher.setStatus(status);
        teacher.setTeacherId(serviceMerchant.getMerchantId());
        teacher.setJoinTime(TimeUtils.now());
        teacher.setStatus(status);
        teacher.setAreaTeamName(serviceMerchant.getBelongAreaTeamName());
        teacher.setAreaTeamId(serviceMerchant.getBelongAreaTeamId());
        teacher.setBusTeamId(0L);
        teacherService.insertSelective(teacher);
        return teacher;
    }

    @Override
    public BusTeam addBusTeamByMerchant(ServiceMerchant serviceMerchant) {
        BusTeam checkBusTeam = busTeamService.findByAreaTeamIdAndBusName(serviceMerchant.getBelongAreaTeamId(), serviceMerchant.getBelongBusTeamName());
        if (checkBusTeam != null) {
            throw new BusException("该业务组名称已存在，审核通过失败");
        }

        BusTeam busTeam=new BusTeam();
        busTeam.setName(serviceMerchant.getBelongBusTeamName());
        busTeam.setAreaTeamId(serviceMerchant.getBelongAreaTeamId());
        busTeam.setAreaTeamName(serviceMerchant.getBelongAreaTeamName());
        busTeam.setCreateTime(TimeUtils.now());
        busTeam.setUpdateTime(TimeUtils.now());
        busTeamService.insertSelective(busTeam);
        return busTeam;
    }

    @Override
    public List<MainAccount> ownMainAccount(SysUser user) {
        List<MainAccount> mainAccountList=null;
        DataPermission dataPermission = sysDataPermissionService.findDataPermissionForUser(user.getUserId());
        if (user.getUserType()==1 ){
            List<Long> areaTeamIdList=dataPermission.getAreaTeamIds();
            List<Long> busTeamIdList=dataPermission.getBusTeamIds();
            List<Long> mainAccountIdList=new ArrayList<>(areaTeamIdList.size());
            mainAccountIdList.addAll(areaTeamIdList);
            mainAccountIdList.addAll(busTeamIdList);
            mainAccountList=mainAccountService.findByIds(mainAccountIdList);
            //mainAccountList=mainAccountService.findByBusTeamIdsAndTags(areaTeamIdList, Arrays.asList("areaTeam","busTeam"));
        }else if (user.getUserType()==2){
            List<Long> busTeamIdList=dataPermission.getBusTeamIds();
            List<Long> mainAccountIdList=new ArrayList<>(busTeamIdList.size());
            mainAccountIdList.addAll(busTeamIdList);
            mainAccountList=mainAccountService.findByIds(mainAccountIdList);
            //mainAccountList=mainAccountService.findByBusTeamIdsAndTags(busTeamIdList, Arrays.asList("busTeam"));
        }else if (user.getUserType()==3){
            MainAccount mainAccount=mainAccountService.findById(user.getUserId());
            mainAccountList=Arrays.asList(mainAccount);
        }else if (user.getUserType()==0){
            List<Long> areaTeamIdList=dataPermission.getAreaTeamIds();
            List<Long> busTeamIdList=dataPermission.getBusTeamIds();
            List<Long> mainAccountIdList=new ArrayList<>(areaTeamIdList.size()+busTeamIdList.size());
            mainAccountIdList.addAll(areaTeamIdList);
            mainAccountIdList.addAll(busTeamIdList);
            mainAccountList=mainAccountService.findByIds(mainAccountIdList);
        }
        return mainAccountList;
    }

    @Override
    public List<TeamVo> ownTeam(SysUser user) {
        List<TeamVo> teamVoList=null;
        DataPermission dataPermission = sysDataPermissionService.findDataPermissionForUser(user.getUserId());
        if (user.getUserType()==1){
            List<Long> areaTeamIdList= dataPermission.getAreaTeamIds();
            List<AreaTeam> areaTeamList=areaTeamService.findByIds(areaTeamIdList);
            teamVoList=this.getTeamVoList(areaTeamList,null);
        }else if (user.getUserType()==2){
            List<Long> busTeamIdList= dataPermission.getBusTeamIds();
            List<BusTeam> busTeamList=busTeamService.findByIds(busTeamIdList);
            teamVoList=this.getTeamVoList(null,busTeamList);
            //mainAccountList=mainAccountService.findByBusTeamIdsAndTags(busTeamIdList, Arrays.asList("busTeam"));
        }else if (user.getUserType()==0){
            List<AreaTeam> areaTeamList=areaTeamService.findAllAreaTeam();
            Example<BusTeam> example=BusTeam.createExample();
            List<BusTeam> busTeamList=busTeamService.findListByExample(example);
            teamVoList=this.getTeamVoList(areaTeamList,busTeamList);
        }
        return teamVoList;
    }

    List<TeamVo> getTeamVoList(List<AreaTeam> areaTeamList,List<BusTeam> busTeamList){
        List<TeamVo> teamVoList=new ArrayList<TeamVo>();
        if (areaTeamList!=null){
            for (AreaTeam areaTeam:areaTeamList){
                TeamVo teamVo=new TeamVo();
                teamVo.setTeamType(0);
                teamVo.setTeamId(areaTeam.getAreaTeamId());
                teamVo.setTeamName(areaTeam.getName());
                teamVoList.add(teamVo);
            }
        }

        if (busTeamList!=null){
            for (BusTeam busTeam:busTeamList){
                TeamVo teamVo=new TeamVo();
                teamVo.setTeamId(busTeam.getBusTeamId());
                teamVo.setTeamName(busTeam.getName());
                teamVo.setTeamType(1);
                teamVoList.add(teamVo);
            }
        }


        return teamVoList;
    }

    @Override
    @Transactional
    public void changeMerchantPassword(String phoneNo, String newPasswordMd5) {
        Example<SysUser> sysUserExample=SysUser.createExample();
        Example.Criteria criteria=sysUserExample.createCriteria();
        criteria.andEqualTo("phoneNo",phoneNo);
        SysUser sysUser=sysUserService.findOneByExample(sysUserExample);
        if (sysUser==null){
            throw new BusException("不存在该用户或者审核不通过");
        }
        sysUserService.changePassword(sysUser.getUserId(),newPasswordMd5);
        ServiceMerchant serviceMerchant=new ServiceMerchant();
        serviceMerchant.setMerchantId(sysUser.getUserId());
        serviceMerchant.setMerchantPassword(newPasswordMd5);
        this.updateSelectiveById(serviceMerchant);
    }
}